<?php
namespace App\Http\Controllers\Api\v1\Article;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\User;
use App\Models\Article;
use App\Models\Category;
use App\Models\Like;
use App\Exceptions\ApiException;
use Illuminate\Pagination\Paginator;
use DB;
use Illuminate\Http\Request;

// 用户中心
class IndexController extends BaseController
{

    /**
     * 展示文章内容
     *
     * @param Article $article
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, Article $article)
    {
        if (!$request->get('id'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id = $request->get('id');
        if (!$id) throw new ApiException('没有该文章看点别的吧~.~', 200, config('code.error'));
        $list = Article::with(['user' => function ($query) {
            $query->select('id', 'nickname', 'avatar');
        }])
            ->where('status', 1)
            ->OrderBy('created_at', 'desc')
            ->find($id);
       if($list) {
          $isLiked = $list->isLike(true, $request->uid); // 检查当前登录用户是否已经点赞
          $list->is_liked = $isLiked; // 将点赞状态添加到查询结果中
        }
        $list->increment('watch', '1');
        // $list['comment'] = $list->comments('p')->with([
        //     'user' => function ($query) {
        //           $query->select('user.id','user.uen','user.tel','user.uc_id','user.nickname','user.sex','user.avatar','user.status','user.has_self_recode','user.forbidden','user.regid', 'recode_astro.sun', 'recode_astro.moon','recode_astro.asc') // 数据字段
        //             ->join('recode', 'user.id', '=', 'recode.uid')
        //             ->join('recode_astro', 'recode.id', '=', 'recode_astro.rid')
        //             ->where('recode.isself','1'); //输出 child comments信息
        //         },
        //     'childs' => function ($query) {
        //         $query->with('user','rUser'); // Load user data for direct child comments
        //     }
        // ])->get();

        return show(200, '文章加载成功', $list);

    }




    public function Cate()
    {
        $articles = Category::get();
        return show(200, '文章加载成功', $articles);
    }
    /**
     * 展示文章列表
     *
     * @param Article $article
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
   public function lists(Request $request, Article $article) {
	$data = Article::with(['user' => function ($query) {
		$query->select('id', 'nickname', 'avatar');
	}
	])
	            ->where(['status' => '1', 'category_id' => $request->input('cid', 0)])
	            ->OrderBy('created_at', 'desc')
	            ->limit(10)
	            ->paginate(15);
	 if($data->isEmpty()){
	     return show(config('code.error'), '没有更多文章',$data);
	 }
	// 检查当前登录用户是否已经点赞每篇文章，并将点赞状态添加到集合中
	if ($request->uid) {
		foreach ($data as $isLiked) {
			$isLiked['is_liked'] = $isLiked->isLike(true, $request->uid);
		}
	}
return show(config('code.success'),'文章加载成功',$data);
}
    /**
     * 点赞
     *
     * @param Article $article
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function like(Request $request)
    {

        $id = intval($request->get('id'));
        if (empty($id)) {
            return show(config('code.error'), '文章id不能为空', [], 403);
        }
        $article = Article::findOrFail($id);
        $res     = $article->isLike(true, $request->uid);
        if ($res == 1) {
            $like = $article->likes()->where(['uid' => $request->uid])->delete();
            $article->decrement('count_like', 1);
            $img       = 'images/111_03.jpg';
            $zanstatus = '-1';
            $message   = '取消点赞';
        } else {
            $article->likes()->create(['uid' => $request->uid]);
            $article->increment('count_like', 1);
            $img       = 'images/111_03-on.jpg';
            $zanstatus = '1';
            $message   = '成功点赞';
        }

        $data = ['count' => $article->count_like, 'img' => $img, 'status' => $zanstatus];
        return show(200, $message, $data);
    }

    // 增加评论 api
    public function store(Request $request)
    {
        $article_id = $request->input('id'); //文章id
        $user_id    = $request->uid; //评论id
        $content    = $request->input('content'); //回复内容
        $p_id       = $request->input('pid', 0); // 回复楼层id
        $r_id       = intval($request->input('rid', 0)); //回复用户id

        $comment = DB::table('comments')
            ->where(['article_id' => $article_id, 'uid' => $request->uid, 'content' => $content])->first();

        if (!empty($comment)) {
            return show(config('code.error'), '不要重复评论', [], 403);
        }
        if ($this->filter_words($content)) {
            return show(config('code.error'), '含有敏感词汇', [], 403);
        }
        $data = [
            'article_id' => $article_id,
            'uid'    => $user_id,
            'content'    => $content,
            'p_id'       => $p_id,
            'r_id'       => $r_id,
        ];
        $validate = new \App\Tools\Validates\Comment();

        if (!$validate->scene('add')->check($data)) {
            return show(config('code.error'), (string) $validate->getError());
        }

        $data    = (new User())->comments()->create($data);
        $article = Article::find($data['article_id']);
        $article->increment('count_comment', 1);
        return show(200, '评论成功', $data);
    }


    public function like_me(Request $request)
    {
        $page     = $request->input('page',1);
        $user     = User::select('id', 'nickname', 'avatar')->where('id', $request->uid)->first();
        $articles = $user->likeArticles()->paginate($page);

        return show(200, '赞过的文章', $articles);
    }
    /**
     * 过滤敏感词汇
     * @param $content
     * @return bool
     */
    protected function filter_words($content)
    {
        $words  = config('words.words');
        $status = false;
        foreach ($words as $w) {
            if (strpos($content, $w) !== false) {
                $status = true;
            }
        }

        if (in_array($content, $words)) {
            $status = true;
        }

        return $status;
    }
}
